import express, { Request, Response, Router } from 'express';
import { Op } from 'sequelize';
import { LiveSessionService } from '../models/LiveSession';
import { GiftService } from '../models/Gift';
import { ApiResponse } from '../types/SharedTypes';
import { generateAss, type ChatItem } from '../subtitles/assGenerator';

const router: Router = express.Router();
const liveSessionService = new LiveSessionService();
const giftService = new GiftService();

/**
 * 根据用户等级返回字幕颜色
 */
function getUserColor(userSnapshot: any): string | undefined {
  if (!userSnapshot) return undefined;

  const payGrade = userSnapshot.payGrade || 0;

  // 41级以上 - 紫色
  if (payGrade >= 41) {
    return '#9B30FF';
  }

  // 31-40级 - 蓝色
  if (payGrade >= 31) {
    return '#1E90FF';
  }

  // 0-30级 - 白色（默认）
  return undefined;
}

// 一次性获取所有房间的session列表
router.get('/', async (req: Request, res: Response) => {
  try {
    const LiveSession = (await import('../models/sequelize/LiveSession')).default;
    const Room = (await import('../models/sequelize/Room')).default;
    const Message = (await import('../models/sequelize/Message')).default;

    const sessions = await LiveSession.findAll({
      include: [
        {
          model: Room,
          as: 'room',
          attributes: ['id', 'title', 'streamerName']
        }
      ],
      order: [['startTime', 'DESC']],
      attributes: ['id', 'roomId', 'title', 'startTime', 'endTime', 'createdAt']
    });

    // 格式化session数据，添加显示标题
    const formattedSessions = await Promise.all(sessions.map(async session => {
      const sessionData = session.toJSON() as any;
      if (!sessionData.endTime) {
        const lastMessage = await Message.findOne({
          where: { sessionId: sessionData.id },
          order: [['createdAt', 'DESC']],
          attributes: ['createdAt'],
        });
        if (lastMessage?.createdAt) {
          sessionData.endTime = lastMessage.createdAt;
          await LiveSession.update(
            { endTime: lastMessage.createdAt },
            { where: { id: sessionData.id } }
          );
        }
      }
      const startDate = new Date(sessionData.startTime).toLocaleDateString('zh-CN');
      const startTime = new Date(sessionData.startTime).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
      const roomTitle = sessionData.title || sessionData.room?.title || '未知标题';

      return {
        ...sessionData,
        displayTitle: `${startDate} ${startTime} - ${roomTitle}`
      };
    }));

    const response: ApiResponse<{ sessions: any[] }> = {
      success: true,
      data: { sessions: formattedSessions },
      message: '获取所有session列表成功'
    };

    res.json(response);
  } catch (error) {
    console.error('获取所有session列表失败:', error);
    const response: ApiResponse<null> = {
      success: false,
      data: null,
      message: '获取所有session列表失败'
    };
    res.status(500).json(response);
  }
});

// 获取指定房间的所有session列表
router.get('/room/:roomId', async (req: Request, res: Response) => {
  try {
    const { roomId } = req.params;
    
    const LiveSession = (await import('../models/sequelize/LiveSession')).default;
    const Room = (await import('../models/sequelize/Room')).default;
    const Message = (await import('../models/sequelize/Message')).default;
    
    const sessions = await LiveSession.findAll({
      where: { roomId },
      include: [
        {
          model: Room,
          as: 'room',
          attributes: ['id', 'title', 'streamerName']
        }
      ],
      order: [['startTime', 'DESC']],
      attributes: ['id', 'roomId', 'title', 'startTime', 'endTime', 'createdAt']
    });
    
    // 格式化session数据，添加显示标题
    const formattedSessions = await Promise.all(sessions.map(async session => {
      const sessionData = session.toJSON() as any;
      if (!sessionData.endTime) {
        const lastMessage = await Message.findOne({
          where: { sessionId: sessionData.id },
          order: [['createdAt', 'DESC']],
          attributes: ['createdAt'],
        });
        if (lastMessage?.createdAt) {
          sessionData.endTime = lastMessage.createdAt;
          await LiveSession.update(
            { endTime: lastMessage.createdAt },
            { where: { id: sessionData.id } }
          );
        }
      }
      const startDate = new Date(sessionData.startTime).toLocaleDateString('zh-CN');
      const startTime = new Date(sessionData.startTime).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
      const roomTitle = sessionData.title || sessionData.room?.title || '未知标题';
      
      return {
        ...sessionData,
        displayTitle: `${startDate} ${startTime} - ${roomTitle}`
      };
    }));
    
    const response: ApiResponse<{ sessions: any[] }> = {
      success: true,
      data: { sessions: formattedSessions },
      message: '获取session列表成功'
    };
    
    res.json(response);
  } catch (error) {
    console.error('获取session列表失败:', error);
    const response: ApiResponse<null> = {
      success: false,
      data: null,
      message: '获取session列表失败'
    };
    res.status(500).json(response);
  }
});

// 导出指定房间当前/最新 session 的 ASS 字幕（仅聊天消息）
router.get('/room/:roomId/subtitles.ass', async (req: Request, res: Response) => {
  try {
    const { roomId } = req.params;
    if (!roomId) {
       res.status(400).send('缺少 roomId 参数');
       return
    }

    const LiveSession = (await import('../models/sequelize/LiveSession')).default;
    const Message = (await import('../models/sequelize/Message')).default;
    const UserSnapshot = (await import('../models/sequelize/UserSnapshot')).default;

    // 优先取正在进行的（endTime 为空），否则取最新一场
    let session = await LiveSession.findOne({
      where: { roomId, endTime: null },
      order: [['startTime', 'DESC']],
    });
    if (!session) {
      session = await LiveSession.findOne({
        where: { roomId },
        order: [['startTime', 'DESC']],
      });
    }
    if (!session) {
       res.status(404).send('该房间暂无历史或当前会话');
       return
    }

    const startTime = session.startTime ?? new Date();

    const messages = await Message.findAll({
      where: {
        sessionId: session.id,
        messageType: 'WebcastChatMessage',
      },
      include: [
        {
          model: UserSnapshot,
          as: 'userSnapshot',
          attributes: ['userName', 'payGrade'],
          required: false,
        },
      ],
      order: [['createdAt', 'ASC']],
    });

    const chatItems: ChatItem[] = messages.map((m: any) => {
      const tSec = Math.max(0, (new Date(m.createdAt).getTime() - new Date(startTime).getTime()) / 1000);
      // 构建作者显示：等级 用户名
      let authorDisplay: string | undefined = undefined;
      if (m.userSnapshot?.userName) {
        const level = m.userSnapshot.payGrade || 0;
        authorDisplay = `${level}级 ${m.userSnapshot.userName}`;
      }
      return {
        time: tSec,
        message: m.content || '',
        author: authorDisplay,
        color: getUserColor(m.userSnapshot),
      };
    });

    const tailHoldSeconds = Number((req.query.tailHoldSeconds ?? 6).toString());
    const width = Number((req.query.width ?? 1080).toString());
    const height = Number((req.query.height ?? 1920).toString());
    const fontSize = Number((req.query.fontSize ?? 36).toString());
    const maxLines = Number((req.query.maxLines ?? 10).toString());
    const animateParam = (req.query.animate ?? '').toString().toLowerCase();
    const alignParam = (req.query.align ?? '').toString().toLowerCase();
    const marginLeftParam = req.query.marginLeft;

    const generatorOpts: any = { tailHoldSeconds, width, height, fontSize, maxLines };
    if (animateParam) {
      generatorOpts.animate = !(animateParam === 'false' || animateParam === '0');
    }
    if (alignParam) {
      generatorOpts.align = alignParam === 'left' ? 'left' : 'right';
    }
    if (marginLeftParam !== undefined) {
      generatorOpts.marginLeft = Number(marginLeftParam.toString());
    }

    const { ass } = generateAss(chatItems, generatorOpts);

    const startDateStr = new Date(startTime).toISOString().replace(/[:T]/g, '-').split('.')[0];
    const rawBaseName = `subtitles-${(session.title || `room-${roomId}`)}-${startDateStr}`;
    const utf8FileName = `${rawBaseName}.ass`;
    const asciiFallback = (rawBaseName
      .replace(/[^A-Za-z0-9\-\_ ]/g, '')
      .trim() || 'subtitles') + '.ass';

    const encodingParam = (req.query.encoding ?? '').toString().toLowerCase();
    const bomParam = (req.query.bom ?? '').toString().toLowerCase();
    let addBOM = true; // 默认带 BOM
    if (encodingParam === 'utf8') addBOM = false;
    if (bomParam === '0' || bomParam === 'false') addBOM = false;
    if (encodingParam === 'utf8bom') addBOM = true;

    res.setHeader('Content-Type', 'text/plain; charset=utf-8');
    res.setHeader(
      'Content-Disposition',
      `attachment; filename="${asciiFallback}"; filename*=UTF-8''${encodeURIComponent(utf8FileName)}`
    );
    const payload = addBOM ? '\uFEFF' + ass : ass;
    res.send(payload);
  } catch (error) {
    console.error('导出房间ASS字幕失败:', error);
    res.status(500).send('导出房间ASS字幕失败');
  }
});

// 获取指定session的完整数据（包括所有弹幕消息、礼物记录和统计信息）
router.get('/:sessionId/details', async (req: any, res: any) => {
  try {
    const { sessionId } = req.params;
    
    const LiveSession = (await import('../models/sequelize/LiveSession')).default;
    const Room = (await import('../models/sequelize/Room')).default;
    const Message = (await import('../models/sequelize/Message')).default;
    const UserRoomGift = (await import('../models/sequelize/UserRoomGift')).default;
    const Gift = (await import('../models/sequelize/Gift')).default;
    const UserSnapshot = (await import('../models/sequelize/UserSnapshot')).default;
    
    // 获取session基本信息
    const session = await LiveSession.findByPk(sessionId, {
      include: [
        {
          model: Room,
          as: 'room',
          attributes: ['id', 'title', 'streamerName', 'streamerAvatar', 'coverUrl', 'type', 'weight']
        }
      ]
    });

    if (!session) {
      const response: ApiResponse<null> = {
        success: false,
        data: null,
        message: 'Session不存在'
      };
      return res.status(404).json(response);
    }
    
    // 获取所有消息（弹幕），排除成员进入消息
    const messages = await Message.findAll({
      where: { 
        sessionId,
        messageType: {
          [Op.ne]: 'WebcastMemberMessage'
        }
      },
      include: [
        {
          model: UserSnapshot,
          as: 'userSnapshot',
          attributes: ['id', 'userId', 'userName', 'userAvatar', 'payGrade', 'fansLevel', 'fansClubName', 'isAdmin']
        }
      ],
      order: [['createdAt', 'ASC']],
   
    });
    
    // 获取所有礼物记录
    const giftRecords = await UserRoomGift.findAll({
      where: { sessionId },
      include: [
        {
          model: Gift,
          as: 'gift',
          attributes: ['id', 'name', 'price', 'icon', 'type']
        },
        {
          model: UserSnapshot,
          as: 'userSnapshot',
          attributes: ['id', 'userId', 'userName', 'userAvatar', 'payGrade', 'fansLevel', 'fansClubName', 'isAdmin']
        }
      ],
      order: [['createdAt', 'ASC']],
  
    });
    

    
    const sessionJson = session.toJSON() as any;
    if (!sessionJson.endTime) {
      const lastMessageForSession = await Message.findOne({
        where: { sessionId },
        order: [['createdAt', 'DESC']],
        attributes: ['createdAt'],
      });
      if (lastMessageForSession?.createdAt) {
        sessionJson.endTime = lastMessageForSession.createdAt;
        await LiveSession.update(
          { endTime: lastMessageForSession.createdAt },
          { where: { id: sessionId } }
        );
      }
    }

    const response: ApiResponse<{
      session: any;
      messages: any[];
      giftRecords: any[];
    }> = {
      success: true,
      data: {
        session: sessionJson,
        messages: messages.map(msg => msg.toJSON()),
        giftRecords: giftRecords.map(gift => gift.toJSON())
      },
      message: '获取session完整数据成功'
    };
    
    res.json(response);
  } catch (error) {
    console.error('获取session详细信息失败:', error);
    const response: ApiResponse<null> = {
      success: false,
      data: null,
      message: '获取session详细信息失败'
    };
    res.status(500).json(response);
  }
});

// 导出指定 session 的 ASS 字幕（仅聊天消息），下载文件
router.get('/:sessionId/subtitles.ass', async (req: Request, res: Response) => {
  try {
    const { sessionId } = req.params;
    if (!sessionId) {
       res.status(400).send('缺少 sessionId 参数');return
    }

    const LiveSession = (await import('../models/sequelize/LiveSession')).default;
    const Message = (await import('../models/sequelize/Message')).default;
    const UserSnapshot = (await import('../models/sequelize/UserSnapshot')).default;

    const session = await LiveSession.findByPk(sessionId);
    if (!session) {
       res.status(404).send('Session不存在');return
    }

    const startTime = session.startTime ?? new Date();

    const messages = await Message.findAll({
      where: {
        sessionId,
        messageType: 'WebcastChatMessage',
      },
      include: [
        {
          model: UserSnapshot,
          as: 'userSnapshot',
          attributes: ['userName', 'payGrade'],
          required: false,
        },
      ],
      order: [['createdAt', 'ASC']],
    });

    const chatItems: ChatItem[] = messages.map((m: any) => {
      const tSec = Math.max(0, (new Date(m.createdAt).getTime() - new Date(startTime).getTime()) / 1000);
      // 构建作者显示：等级 用户名
      let authorDisplay: string | undefined = undefined;
      if (m.userSnapshot?.userName) {
        const level = m.userSnapshot.payGrade || 0;
        authorDisplay = `${level}级 ${m.userSnapshot.userName}`;
      }
      return {
        time: tSec,
        message: m.content || '',
        author: authorDisplay,
        color: getUserColor(m.userSnapshot),
      };
    });

    const tailHoldSeconds = Number((req.query.tailHoldSeconds ?? 6).toString());
    const width = Number((req.query.width ?? 1080).toString());
    const height = Number((req.query.height ?? 1920).toString());
    const fontSize = Number((req.query.fontSize ?? 36).toString());
    const maxLines = Number((req.query.maxLines ?? 10).toString());
    const animateParam3 = (req.query.animate ?? '').toString().toLowerCase();
    const alignParam3 = (req.query.align ?? '').toString().toLowerCase();
    const marginLeftParam3 = req.query.marginLeft;

    const generatorOpts3: any = { tailHoldSeconds, width, height, fontSize, maxLines };
    if (animateParam3) {
      generatorOpts3.animate = !(animateParam3 === 'false' || animateParam3 === '0');
    }
    if (alignParam3) {
      generatorOpts3.align = alignParam3 === 'left' ? 'left' : 'right';
    }
    if (marginLeftParam3 !== undefined) {
      generatorOpts3.marginLeft = Number(marginLeftParam3.toString());
    }

    const { ass } = generateAss(chatItems, generatorOpts3);

    const startDateStr = new Date(startTime).toISOString().replace(/[:T]/g, '-').split('.')[0];
    const rawBaseName = `subtitles-${(session.title || 'session')}-${startDateStr}`;
    const utf8FileName = `${rawBaseName}.ass`;
    const asciiFallback = (rawBaseName
      .replace(/[^A-Za-z0-9\-\_ ]/g, '')
      .trim() || 'subtitles') + '.ass';

    const encodingParam2 = (req.query.encoding ?? '').toString().toLowerCase();
    const bomParam2 = (req.query.bom ?? '').toString().toLowerCase();
    let addBOM2 = true;
    if (encodingParam2 === 'utf8') addBOM2 = false;
    if (bomParam2 === '0' || bomParam2 === 'false') addBOM2 = false;
    if (encodingParam2 === 'utf8bom') addBOM2 = true;

    res.setHeader('Content-Type', 'text/plain; charset=utf-8');
    res.setHeader(
      'Content-Disposition',
      `attachment; filename="${asciiFallback}"; filename*=UTF-8''${encodeURIComponent(utf8FileName)}`
    );
    const payload2 = addBOM2 ? '\uFEFF' + ass : ass;
    res.send(payload2);
  } catch (error) {
    console.error('导出ASS字幕失败:', error);
    res.status(500).send('导出ASS字幕失败');
  }
});

router.get('/:sessionId/gift-stats', async (req: Request, res: Response) => {
  try {
    const { sessionId } = req.params;
    const stats = await giftService.getSessionGiftSummary(sessionId);

    const response: ApiResponse<typeof stats> = {
      success: true,
      data: stats,
      message: '获取礼物统计成功'
    };

    res.json(response);
  } catch (error) {
    console.error('获取礼物统计失败:', error);
    const response: ApiResponse<null> = {
      success: false,
      data: null,
      message: '获取礼物统计失败'
    };
    res.status(500).json(response);
  }
});

router.delete('/:sessionId', async (req: Request, res: Response) => {
  try {
    const { sessionId } = req.params;

    if (!sessionId) {
      const response: ApiResponse<null> = {
        success: false,
        data: null,
        message: '缺少 sessionId 参数'
      };
       res.status(400).json(response);return
    }

    const LiveSession = (await import('../models/sequelize/LiveSession')).default;
    const Message = (await import('../models/sequelize/Message')).default;
    const UserRoomGift = (await import('../models/sequelize/UserRoomGift')).default;
    const Statistic = (await import('../models/sequelize/Statistic')).default;

    await Message.destroy({ where: { sessionId } });
    await UserRoomGift.destroy({ where: { sessionId } });
    await Statistic.destroy({ where: { sessionId } });

    const deleted = await LiveSession.destroy({ where: { id: sessionId } });

    if (deleted === 0) {
      const response: ApiResponse<null> = {
        success: false,
        data: null,
        message: 'Session不存在或已被删除'
      };
       res.status(404).json(response);
       return
    }

    const response: ApiResponse<null> = {
      success: true,
      data: null,
      message: 'Session删除成功'
    };
    res.json(response);
  } catch (error) {
    console.error('删除session失败:', error);
    const response: ApiResponse<null> = {
      success: false,
      data: null,
      message: '删除session失败'
    };
    res.status(500).json(response);
  }
});

export default router;
